import axios, { AxiosInstance } from "axios";
import { ElMessage } from "element-plus";
import { AxiosRequestOptions } from "@/api/types";
import { showLoading, hideLoading } from "@/utils/loading";

if (typeof window !== 'undefined') {
  window.axios = axios
}

let defaultOptions: AxiosRequestOptions = {
  showTips: false,
  showLoading: false
}

let service = axios.create({
  baseURL: (import.meta.env.VITE_APP_BASE_HOST) as string + import.meta.env.VITE_APP_BASE_PATH, // 超时
  timeout: 10000
})
service.interceptors.request.use(config => {
  if (defaultOptions.showLoading)
    showLoading()
  return config;
})
service.interceptors.response.use(response => {
  if (defaultOptions.showLoading)
    setTimeout(() => {
      defaultOptions.showLoading = false
      hideLoading();
    }, 200);

  if (response.data.code == 0) {
    if (defaultOptions.showTips) {
      ElMessage({
        message: response.data.msg,
        type: 'success',
        duration: 3 * 1000,
        showClose: true
      })
      defaultOptions.showTips = false
    }
  } else {
    ElMessage({
      message: response.data.msg, type: 'error', duration: 5 * 1000, showClose: true
    })
    console.error('error', response.data.msg)
  }
  return response.data
}, (error) => {
  if (defaultOptions.showLoading)
    setTimeout(() => {
      defaultOptions.showLoading = false
      hideLoading();
    }, 200);
  let { message } = error
  if (message.includes("timeout")) {
    message = "system interface request timeout";
  }
  ElMessage({
    message: message, type: 'error', duration: 5 * 1000, showClose: true
  })
  return Promise.reject(error)
})


export function post<R>(url: string, params?: any, options?: AxiosRequestOptions) {
  options && (defaultOptions = options)
  return service.post<void, R>(url, params)
}

export function get<R>(url: string, params?: any, options?: AxiosRequestOptions) {
  options && (defaultOptions = options)
  return service.get<void, R>(url, { params })
}

export function put<R>(url: string, params?: any, options?: AxiosRequestOptions) {
  options && (defaultOptions = options)
  return service.put<void, R>(url, { params })
}

export function del<R>(url: string, params?: any, options?: AxiosRequestOptions) {
  options && (defaultOptions = options)
  return service.delete<void, R>(url, { params })
}


export function injectAppAxios(axios: AxiosInstance) {
  service = axios
}

export default service